﻿using System;
using System.Configuration;

namespace SaveConnectionStringDemo
{
	internal class Program
	{
		private static void Main()
		{
			AddAndSaveOneConnectionStringSettingsUnitTest();
			Console.WriteLine("Press <Enter> to exit.");
			Console.ReadLine();
		}

		private static void AddAndSaveOneConnectionStringSettingsUnitTest()
		{
			// Generate a random name to show AddAndSaveOneConnectionStringSettings works.
			// You never do this in production code.
			var connectionStringName = "TestConnectionConnectionString." + DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss");

			// Create a connection string element.
			ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(connectionStringName,
				"LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" + "Initial Catalog=aspnetdb",
				"System.Data.SqlClient");

			Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

			DumpToConsole(ConfigurationManager.ConnectionStrings, "Before AddAndSaveOneConnectionStringSettings.");

			SaveConnectionString.AddAndSaveOneConnectionStringSettings(configuration,
				connectionStringSettings);

			DumpToConsole(ConfigurationManager.ConnectionStrings, "After AddAndSaveOneConnectionStringSettings.");
		}

		private static void DumpToConsole(ConnectionStringSettingsCollection connectionStringSettingsCollection,
			string caption)
		{
			Console.WriteLine("\n" + caption + " " + connectionStringSettingsCollection.Count + " entries found.");
			foreach (ConnectionStringSettings connectionStringSettings in connectionStringSettingsCollection)
			{
				Console.WriteLine("Connection Name:   " + connectionStringSettings.Name);
				Console.WriteLine("Connection String: " + connectionStringSettings.ConnectionString + "\n");
			}
		}
	}
}